define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'kzvote/person/index' + location.search,
                    add_url: 'kzvote/person/add?vote_id='+Config.vote_id,
                    edit_url: 'kzvote/person/edit',
                    edit_vote_url: 'kzvote/person/edit_vote',
                    del_url: 'kzvote/person/del',
                    multi_url: 'kzvote/person/multi',
                    // import_url: 'kzvote/person/import',
                    import_url: 'kzvote/person/import',

                    table: 'kzvote_person',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                showExport: false,//隐藏导出
                showToggle: false,//隐藏浏览模式
                showColumns: false,//隐藏显示隐藏模式
                searchFormVisible: true,//默认显示搜索表单
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'user_id', title: __('User_id'),visible:false, operate: false},
                        {field: 'vote_id', title: __('投票活动ID'),visible:false},
                        {field: 'vote.name', title: __('Vote_id'), operate: 'LIKE'},
                        {field: 'user.nickname', title: __('用户昵称'), operate: 'LIKE'},
                        {field: 'user.avatar', title: __('用户头像'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'phone', title: __('联系方式'), operate: 'LIKE'},
                        {field: 'code', title: __('Code')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images},
                        {field: 'video', title: __('视频'), formatter: Controller.api.formatter.video, operate: false},
                        {field: 'count', title: __('Count')},
                        {field: 'er_code', title: __('Er_code'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'status', title: __('Status'), searchList: {"10":__('Status 10'),"20":__('Status 20'),"30":__('Status 30')}, formatter: Table.api.formatter.status},
                        {field: 'type', title: __('Type'), searchList: {"0":__('Type 0'),"1":__('Type 1')}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'edit2',
                                    title: __('送礼'),
                                    text: __('送礼'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-magic',
                                    url: 'kzvote/gift/order/give?vote_id={vote_id}&person_id={id}',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        if (row.status == 20 && row.vote.gift_status == '1' && row.vote.mold < 3) {
                                            return true;
                                        }
                                    }
                                }],
                            formatter: Table.api.formatter.operate, operate: false
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

           // 打开导入页面
            $('.btn-importPage').click(function () {
                Fast.api.open('kzvote/person/importmulti', '导入选手', {
                    area: ['800px', '480px'],
                    callback: function (data) {
                        table.bootstrapTable('refresh');
                    }
                });
            });


            //导出数据
            exports(Table, table)

            //批量分组
            // $(".btn-grouping").click(function () {
            //     // 获取选中的数据id
            //     var ids = Table.api.selectedids(table).join(",");
            //     // 获取接口url，并将数据id拼接到url中
            //     var url = $(this).attr('data-url') + '?ids=' + ids;
            //     if (!url) return false;
            //     // 获取弹窗标题
            //     var title = $(this).attr('data-title');
            //     // 打开窗口
            //     Fast.api.open(url, title, {
            //         area: ['40%', '40%'],
            //         callback: function (value) {
            //             table.bootstrapTable('refresh');
            //             Fast.api.close();
            //         }
            //     })
            // });
            // 附件归类
            $(document).on('click', '.btn-grouping', function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('批量活动'),
                    content: Template("typetpl", {}),
                    btn: [__('OK')],
                    yes: function (index, layero) {
                        var group = $("select[name='group']", layero).val();
                        Fast.api.ajax({
                            url: "kzvote/person/grouping",
                            type: "post",
                            data: {group: group, ids: ids.join(',')},
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },

        importmulti: function () {
            Controller.api.bindevent();

            $("input[name='group_id']").addClass("selectpage").data("source", "kzvote/group/index").data('field', 'name').data("params", function () {
                let vote_id = $("#c-vote_id").val()
                return vote_id ? {"custom[vote_id]": vote_id} : {};
            });

            // 手动绑定导入事件
            Upload.api.plupload($('.btn-import'), function (data, ret) {
                let vote_id = $('#c-vote_id').val();
                let group_id = $('#c-group_id').val();

                $('#file_url').val(data.url);
                let html = `本次上传识别到 ${data.count} 投票选手图片，点击确定按钮开始导入<br><br>`
                if (data.list.length) {
                    html += '选手列表：<br><br>'
                    for (let i = 0; i < data.list.length; i++) {
                        const filename = data.list[i]
                        html += `${filename} <br>`
                    }
                }

                $('#person_count').html(html)
            }, null, null, 'kzvote/person/uploadzip');
        },
        api: {
            bindevent: function () {
                $("#c-group_id").change(function () {
                    $("#c-group_name").val($(this).find("option:selected").text())
                })

                Form.api.bindevent($("form[role=form]"));
            },
            formatter:{
                video: function (value, row, index) {
                    return value ? '<a target="_blank" href="' + value + '" title="' + row.title + '"><i class="fa fa-ticket"></i>点击播放</a>' : '-';
                },
            }
        }
    };

    return Controller;
});

function exports(Table, table) {
//*************************** 自定义export开始
    var submitForm = function (ids, layero) {
        var options = table.bootstrapTable('getOptions');
        var columns = [];
        $.each(options.columns[0], function (i, j) {
            if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
                columns.push(j.field);
            }
        });
        var search = options.queryParams({});
        $("input[name=search]", layero).val(options.searchText);
        $("input[name=ids]", layero).val(ids);
        $("input[name=filter]", layero).val(search.filter);
        $("input[name=op]", layero).val(search.op);
        $("input[name=columns]", layero).val(columns.join(','));
        $("form", layero).submit();
    };
    $(document).on("click", ".btn-export", function () {
        var ids = Table.api.selectedids(table);
        var page = table.bootstrapTable('getData');
        var all = table.bootstrapTable('getOptions').totalRows;
        Layer.confirm("是否确定导出<form action='person/export' method='post' target='_blank'>" +
            "<input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'>" +
            "<input type='hidden' name='search'><input type='hidden' name='columns'></form>", {

            title: '导出数据',
            btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
            success: function (layero, index) {
                $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
            },
            yes: function (index, layero) {
                layer.close(layer.index);
                submitForm(ids.join(","), layero);
                return false;
            },
            btn2: function (index, layero) {
                layer.close(layer.index);
                var ids = [];
                $.each(page, function (i, j) {
                    ids.push(j.id);
                });
                submitForm(ids.join(","), layero);
                return false;
            },
            btn3: function (index, layero) {
                layer.close(layer.index);
                submitForm("all", layero);
                return false;
            }
        });
    });
    //*************************** 自定义export结束
}